package com.augurit.gzcgwsp.ljzyz.service.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gis.common.util.DateUtil;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.jzfqwczz.common.entity.YwYnBusinfoHfqk;
import com.augurit.gzcgwsp.jzfqwczz.common.entity.YwYnBusinfoNssy;
import com.augurit.gzcgwsp.jzfqwczz.common.service.IYwYnBusinfoHfqkService;
import com.augurit.gzcgwsp.jzfqwczz.common.service.IYwYnBusinfoNssyService;
import com.augurit.gzcgwsp.jzfqwczz.common.web.form.YwYnBusinfoHfqkForm;
import com.augurit.gzcgwsp.jzfqwczz.common.web.form.YwYnBusinfoNssyForm;
import com.augurit.gzcgwsp.ljzyz.convert.YwYnBusinfoConvertor;
import com.augurit.gzcgwsp.ljzyz.convert.YwYnBustransferConvertor;
import com.augurit.gzcgwsp.ljzyz.dao.YwYnBusinfoDao;
import com.augurit.gzcgwsp.ljzyz.entity.YwYnBusinfo;
import com.augurit.gzcgwsp.ljzyz.entity.YwYnBustransfer;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnBustransferService;
import com.augurit.gzcgwsp.ljzyz.web.form.YwYnBusinfoForm;
import com.augurit.gzcgwsp.ywcmn.convert.YwComQyxxConvertor;
import com.augurit.gzcgwsp.ywcmn.entity.YwComQyxx;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;

@Service
@Transactional
public class YwYnBusinfoServiceImpl implements IYwYnBusinfoService{

	@Autowired
	private YwYnBusinfoDao ywYnBusinfoDao;
	@Autowired
	private IYwYnBusinfoNssyService ywYnBusinfoNssyService;
	@Autowired
	private IYwYnBusinfoHfqkService ywYnBusinfoHfqkService;
	@Autowired
	private IYwComQyxxService ywComQyxxService;
	@Autowired
	private IYwYnBustransferService ywYnBustransferService;

	
	/**
	 * 根据主键获取Form对象
	 */
	@Transactional(readOnly = true)
	public YwYnBusinfoForm get(Long id) {
		YwYnBusinfo entity = ywYnBusinfoDao.get(id);
		if(StringUtils.isBlank(entity.getGsmc())){
			entity.setGsmc(ywComQyxxService.get(entity.getQyid()).getSqdw());
		}
		return YwYnBusinfoConvertor.convertVoToForm(entity);
	}
	
	/**
	 * 删除Form对象列表
	 */
	public void delete(Long... ids) {
		ywYnBusinfoDao.delete(ids);
	}

	/**
	 * 保存新增或修改的Form对象列表
	 */
	public void save(YwYnBusinfoForm... forms) {
		if(forms != null)
			for(YwYnBusinfoForm form : forms)
				this.save(form);
	}
	
	/**
	 * 保存新增或修改的Form对象
	 */
	public void save(YwYnBusinfoForm form){
		if(form != null){
			YwYnBusinfo entity = null;
			
			//准备VO对象
			if(form != null && form.getId() != null){
				entity = ywYnBusinfoDao.get(form.getId());
			}else{
				entity = new YwYnBusinfo();
			}
			
			//属性值转换
			YwYnBusinfoConvertor.convertFormToVo(form, entity);
			//设置时间对应的字符串格式
			entity = this.setDates(entity);
			entity.setNssts(form.getNssts());
			//保存
			ywYnBusinfoDao.save(entity);
			
			//回填ID属性值
			form.setId(entity.getId());
		}
	}
	
	/**
	 * 修改对象
	 */
	public void update(YwYnBusinfo entity){
		//设置时间对应的字符串格式
		entity = this.setDates(entity);
		//修改
		ywYnBusinfoDao.save(entity);
	}
	
	/**
	 * 设置时间对应的字符串格式
	 * @param entity
	 * @return
	 */
	public YwYnBusinfo setDates(YwYnBusinfo entity){
		Date ccrq = entity.getCcrq();
		Date djrq = entity.getDjrq();
		Date zyzyxq = entity.getZyzyxq();
		Date xszyxrq = entity.getXszyxrq();
		Date shrq = entity.getShrq();
		Date shyxq = entity.getShyxq();
		if(ccrq != null){
			entity.setCcrqStr(DateUtil.date2ChinaString(ccrq,3));
		}else{
			entity.setCcrqStr("");
		}			
		if(djrq != null){
			entity.setDjrqStr(DateUtil.date2ChinaString(djrq,3));
		}else{
			entity.setDjrqStr("");
		}			
		if(zyzyxq != null){
			entity.setZyzyxqStr(DateUtil.date2ChinaString(zyzyxq,3));
		}else{
			entity.setZyzyxqStr("");
		}			
		if(xszyxrq != null){
			entity.setXszyxrqStr(DateUtil.date2ChinaString(xszyxrq,3));
		}else{
			entity.setXszyxrqStr("");
		}			
		if(shrq != null){
			entity.setShrqStr(DateUtil.date2ChinaString(shrq,3));
		}else{
			entity.setShrqStr("");
		}
		if(shyxq != null){
			entity.setShyxqStr(DateUtil.date2ChinaString(shyxq,3));
		}else{
			entity.setShyxqStr("");
		}
		
		return entity;
	}

	/**
	 * 根据Form对象的查询条件作分页查询
	 */
	@Transactional(readOnly = true)
	public Page<YwYnBusinfoForm> search(Page<YwYnBusinfoForm> page, YwYnBusinfoForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx where 1=1 and (ps.delsts is null or ps.delsts!='1') and ps.qyid = qyxx.id ");
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			
			if(StringUtils.isNotBlank(form.getGsmc())){
				hql.append(" and qyxx.sqdw like '%"+form.getGsmc()+"%'");
			}
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		}
		
		//排序
		if(form.getQyid()!=null){
			hql.append(" order by  ps.clbh desc");
		}else{
			hql.append(" order by  qyxx.id desc");
		}
		
		
		// 执行分页查询操作
		ywYnBusinfoDao.findPage(pg, hql.toString(), values);
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = this.convertVoListToFormList(pg.getResult());
		
		
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	public  List<YwYnBusinfoForm> convertVoListToFormList(List<YwYnBusinfo> ywYnBusinfoList) {
		if(ywYnBusinfoList != null && ywYnBusinfoList.size() > 0) {
			List<YwYnBusinfoForm> ywYnBusinfoFormList = new ArrayList();
			for(int i=0; i<ywYnBusinfoList.size(); i++) {
				YwYnBusinfoForm form=YwYnBusinfoConvertor.convertVoToForm(ywYnBusinfoList.get(i));
				if(StringUtils.isBlank(form.getGsmc())){
					Long qyId=form.getQyid();
					String sqdw=ywComQyxxService.get(qyId).getSqdw();
					form.setGsmc(sqdw);
				}
				if(StringUtils.isBlank(form.getYwtzs())){
					form.setYwtzs("无");
				}
				
				
				//查询准运证有效期
				String zyzyxq=getZyzyxqByBusId(form.getId());
				form.setZyzyxqStr(zyzyxq);
				ywYnBusinfoFormList.add(form);
			}
			return ywYnBusinfoFormList;
		}
		return null;
	}
	/**
	 * 根据过滤条件列表作分页查询
	 */
	@Transactional(readOnly = true)
	public Page<YwYnBusinfoForm> search(Page<YwYnBusinfoForm> page, List<PropertyFilter> filters) {
		// 建立新的分页对象
		Page<YwYnBusinfo> pg = PageUtils.newPageInstance(page);
		
		// 按过滤条件分页查找对象
		ywYnBusinfoDao.findPage(pg, filters);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = YwYnBusinfoConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	/**
	 * 根据案件id查找
	 */
	public List<YwYnBusinfo> findPageByAjid(String qyid,String pageNo) {
	
		return ywYnBusinfoDao.findPageByAjid(qyid,pageNo);
	}
	
	/**
	 * 根据企业id查找车辆列表
	 * @param ajid
	 * @return
	 */
	public List<YwYnBusinfo> findPageByQyid(String qyid){
		return ywYnBusinfoDao.findPageByQyid(qyid);
	}
	/**
	 * 根据主键查找车辆信息
	 * @param id
	 * @return
	 */
	public YwYnBusinfo findById(String id){
		return ywYnBusinfoDao.findById(id);
	}
	/**
	 * 导入车辆信息excel
	 * @param ajid 案件ID
	 * @param gsmc 公司名称
	 * @param uploadFile 流
	 * @throws Exception
	 */
	public void uploadBusinfo(long qyid,long ajid, String gsmc, InputStream uploadFile) throws Exception {
		// 通过得到的文件输入流inputstream创建一个HSSFWordbook对象
		// InputStream is = new FileInputStream("d://模板.xls");
		HSSFWorkbook hssfworkbook = new HSSFWorkbook(uploadFile);// 将is流实例到
		// 一个excel流里
		HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);// 第一个工作表
		HSSFRow hssfrow = hssfsheet.getRow(0);// 第一行
		String sheetName = hssfsheet.getSheetName();
//		System.out.println("sheet的名字 = "+sheetName);
		String cjh = "";//车架号
		String cphm = "";//车牌号码
		String zyzh = "";//准运证号
		Date zyzyxq = null;//准运证有效期
		String cx = "";//车型
		Date ccrq = null;//出厂日期
		Date djrq = null;//登记日期
		String fdjh = "";//发动机号
		String zzl = "";//准重量
		String gpshxcjlyhm = "";//GPS或行车记录仪号码
		String bz = "";//备注
		Date xszyxrq = null;//行驶证有效日期
		for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
				hssfrow = hssfsheet.getRow(j);
				// 判断是否还存在需要导入的数据
				if (hssfrow == null) {
					//System.out.println("这里已没有数据，在第" + i + "列,第" + j + "行");
					break;
				}
				if (j >=1) {//第一行
					if (hssfrow.getCell((short) 0) == null) {
						cjh = "";
					} else if (hssfrow.getCell((short) 0).getCellType() == 0) {
						cjh = new Double(hssfrow.getCell((short) 0)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						cjh = hssfrow.getCell((short) 0)
								.getStringCellValue().trim();
					}
					
					if (hssfrow.getCell((short) 1) == null) {
						cphm = "";
					} else if (hssfrow.getCell((short) 1).getCellType() == 0) {
						cphm = new Double(hssfrow.getCell((short) 1)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						cphm = hssfrow.getCell((short) 1)
								.getStringCellValue().trim();
					}
					
					if (hssfrow.getCell((short) 2) == null) {
						zyzh = "";
					} else if (hssfrow.getCell((short) 2).getCellType() == 0) {
						zyzh = new Double(hssfrow.getCell((short) 2)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						zyzh = hssfrow.getCell((short) 2)
								.getStringCellValue().trim();
					}
					
					if (hssfrow.getCell((short) 3) == null) {
						zyzyxq = null;
					} else {// 如果EXCEL表格中的数据类型为字符串型
						zyzyxq = hssfrow.getCell((short) 3)
								.getDateCellValue();
					}
					
					if (hssfrow.getCell((short) 4) == null) {
						cx = "";
					} else if (hssfrow.getCell((short) 4).getCellType() == 0) {
						cx = new Double(hssfrow.getCell((short) 4)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						cx = hssfrow.getCell((short) 4)
								.getStringCellValue().trim();
					}
					
					if (hssfrow.getCell((short) 5) == null) {
						ccrq = null;
					}else {// 如果EXCEL表格中的数据类型为字符串型
						ccrq = hssfrow.getCell((short) 5)
								.getDateCellValue();
					}
					
					if (hssfrow.getCell((short) 6) == null) {
						djrq = null;
					}else {// 如果EXCEL表格中的数据类型为字符串型
						djrq = hssfrow.getCell((short) 6)
								.getDateCellValue();
					}
					
					if (hssfrow.getCell((short) 7) == null) {
						xszyxrq = null;
					}else {// 如果EXCEL表格中的数据类型为字符串型
						xszyxrq = hssfrow.getCell((short) 7)
								.getDateCellValue();
					}
					
					if (hssfrow.getCell((short) 8) == null) {
						fdjh = "";
					} else if (hssfrow.getCell((short) 8).getCellType() == 0) {
						fdjh = new Double(hssfrow.getCell((short) 8)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						fdjh = hssfrow.getCell((short) 8)
								.getStringCellValue().trim();
					}
					
					if (hssfrow.getCell((short) 9) == null) {
						zzl = "";
					} else if (hssfrow.getCell((short) 9).getCellType() == 0) {
						zzl = new Double(hssfrow.getCell((short) 9)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						zzl = hssfrow.getCell((short) 9)
								.getStringCellValue().trim();
					}
					
					if (hssfrow.getCell((short) 10) == null) {
						gpshxcjlyhm = "";
					} else if (hssfrow.getCell((short) 10).getCellType() == 0) {
						gpshxcjlyhm = new Double(hssfrow.getCell((short) 10)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						gpshxcjlyhm = hssfrow.getCell((short) 10)
								.getStringCellValue().trim();
					}
					
					if (hssfrow.getCell((short) 11) == null) {
						bz = "";
					} else if (hssfrow.getCell((short) 11).getCellType() == 0) {
						bz = new Double(hssfrow.getCell((short) 11)
								.getNumericCellValue()).toString();
					} else {// 如果EXCEL表格中的数据类型为字符串型
						bz = hssfrow.getCell((short) 11)
								.getStringCellValue().trim();
					}
				}
//				System.out.println("ajid = "+ajid);
//				System.out.println("gsmc = "+gsmc);
//				System.out.println("cjh = "+cjh);
//				System.out.println("cphm = "+cphm);
//				System.out.println("zyzh = "+zyzh);
//				System.out.println("cx = "+cx);
//				System.out.println("fdjh = "+fdjh);
//				System.out.println("zzl = "+zzl);
//				System.out.println("gpshxcjlyhm = "+gpshxcjlyhm);
//				System.out.println("bz = "+bz);				
//				System.out.println("zyzyxq = "+zyzyxq);
//				System.out.println("ccrq = "+ccrq);
//				System.out.println("djrq = "+djrq);
				YwYnBusinfo entity = new YwYnBusinfo();
				entity.setQyid(qyid);
				entity.setAjid(ajid);
				entity.setGsmc(gsmc);
				entity.setCjh(cjh);
				entity.setCphm(cphm);
				entity.setZyzh(zyzh);
				entity.setCx(cx);
				entity.setFdjh(fdjh);
				entity.setZzl(zzl);
				entity.setGpsno(gpshxcjlyhm);
				entity.setZyzyxq(zyzyxq);
				entity.setCcrq(ccrq);
				entity.setDjrq(djrq);				
				entity.setXszyxrq(xszyxrq);		
				entity = this.setDates(entity);
				ywYnBusinfoDao.save(entity);//保存
		}
		
	}
	/**
	 * 更新车辆信息
	 * @param busId 车辆ID
	 * @param spsx 审批事项
	 */
	public void updateBusinfo(long busId,String spsx){
		String sql = "update YwYnBusinfo ps set ps.spsx='"+spsx+"' where ps.id="+busId;
		Query query = ywYnBusinfoDao.getSession().createQuery(sql);
		query.executeUpdate();
	}
	
	public YwYnBusinfoForm sp(Long id,String hfsqksts,String nssysts) throws Exception{
		YwYnBusinfo entity = ywYnBusinfoDao.get(id);
		YwYnBusinfoNssyForm nssy=this.ywYnBusinfoNssyService.getEntity(String.valueOf(id),nssysts);
		YwYnBusinfoHfqkForm ywYnBusinfoHfqk= ywYnBusinfoHfqkService.getEntity(id,hfsqksts);
		if(ywYnBusinfoHfqk.getJcrq()==null){
			ywYnBusinfoHfqk.setJcrq(new Date());
		}else{
			ywYnBusinfoHfqk.setNssyId(nssy.getId());
		}
		YwYnBusinfoForm ywYnBusinfoForm = YwYnBusinfoConvertor.convertVoToForm(entity);
		
		YwYnBusinfoConvertor.convertHfqkFormToForm(ywYnBusinfoHfqk, ywYnBusinfoForm);
		YwYnBusinfoConvertor.convertNssyFormToForm(nssy, ywYnBusinfoForm);
		ywYnBusinfoForm.setNssyId(nssy.getId());
		return ywYnBusinfoForm;
	}

	private void search(YwYnBusinfoHfqkForm ywYnBusinfoHfqkForm) {
		// TODO Auto-generated method stub
		
	}

	/*
	 * 获取车辆信息(non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService#getQyxx()
	 */
	@Override
	public List<YwComQyxx> getQyxx() {
		String sql=" from YwComQyxx where templateCode like '%jzljczz%'";
		List list=ywYnBusinfoDao.find(sql);
		return list;
	}

	@Override
	public Page<YwYnBusinfoForm> getCarNsdj(Page<YwYnBusinfoForm> page,
			YwYnBusinfoForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx where 1=1  and ps.qyid = qyxx.id ");
		hql.append(" and ps.nssts='1'");
		List values = new ArrayList();
		// 查询条件
		if(form != null && form.getQyid()!=null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		}
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		// 执行分页查询操作
		ywYnBusinfoDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = YwYnBusinfoConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		
		return page;
		
	}

	@Override
	public Page<YwYnBusinfoForm> getNshf(Page<YwYnBusinfoForm> page,
			YwYnBusinfoForm form) {

		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx where 1=1  and ps.qyid = qyxx.id ");
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			
			if(StringUtils.isNotBlank(form.getGsmc())){
				hql.append(" and qyxx.sqdw like '%"+form.getGsmc()+"%'");
			}
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		}
		
		 hql.append(" and ps.nssts='2'");
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		// 执行分页查询操作
		ywYnBusinfoDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = YwYnBusinfoConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	@Override
	public Page<YwYnBusinfoForm> getspList(Page<YwYnBusinfoForm> page,
			YwYnBusinfoForm form,String hfqksts,String nssts) {

		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx where  ps.qyid = qyxx.id ");
		List values = new ArrayList();
		// 查询条件
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			if(StringUtils.isNotBlank(form.getGsmc())){
				hql.append(" and qyxx.sqdw like '%"+form.getGsmc()+"%'");
			}
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		}
		 hql.append(" and ps.nssts='"+nssts+"'");
		 //hql.append(" and hfqk.sts='"+hfqksts+"'");
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		// 执行分页查询操作
		ywYnBusinfoDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = YwYnBusinfoConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	@Override
	public YwYnBusinfo getEntity(Long busId) {
		return (YwYnBusinfo) this.ywYnBusinfoDao.getSession().get(YwYnBusinfo.class, busId);
	}

	/*
	 * (non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService#getSpData(java.lang.Long)
	 */
	@Override
	public List<YwYnBusinfoForm> getSpData(Long id,Date date) {
		YwYnBusinfo entity = ywYnBusinfoDao.get(id);
			List<YwYnBusinfoForm> list=new ArrayList<YwYnBusinfoForm> ();
			String years="";
			if(date!=null){
				Calendar cal = Calendar.getInstance();
			 	cal.setTime(date);
			    int year=cal.get(Calendar.YEAR);
			    years=String.valueOf(year);
			}
		 
		List<YwYnBusinfoHfqkForm> forms= ywYnBusinfoHfqkService.getHfqkByBusId(id,years);
		for(YwYnBusinfoHfqkForm form:forms){
			YwYnBusinfoNssyForm nssy=this.ywYnBusinfoNssyService.get(form.getNssyId());
			YwYnBusinfoForm ywYnBusinfoForm = YwYnBusinfoConvertor.convertVoToForm(entity);
			YwYnBusinfoConvertor.convertHfqkFormToForm(form, ywYnBusinfoForm);
			YwYnBusinfoConvertor.convertNssyFormToForm(nssy, ywYnBusinfoForm);
			//ywYnBusinfoForm.getYxjsrq();
			//获取原来标志号的信息
			YwYnBustransfer transfer=ywYnBustransferService.getEntity(id,nssy.getId());
			if(transfer!=null){
				if(transfer.getQyid()!=ywYnBusinfoForm.getQyid()){
					String isTransfer="过户";
					ywYnBusinfoForm.setIsTransfer(isTransfer);
				}
				String bzh=transfer.getBzh();//原来的标识号
				Date ghrq=transfer.getGhrq();//过户日期
				ywYnBusinfoForm.setGhrq(ghrq);
				ywYnBusinfoForm.setOldClbh(bzh);
				
			}else{
				ywYnBusinfoForm.setOldClbh(ywYnBusinfoForm.getClbh());
			}
			
			list.add(ywYnBusinfoForm);
		}
		return list;
	}

	@Override
	public void saveForm(YwYnBusinfoForm form) {
		if(form.getId()!=null){
			YwYnBusinfo bus=ywYnBusinfoDao.get(form.getId());
			Long qyid=bus.getQyid();
			Long newqyid=form.getQyid();
			if(qyid.longValue()!=newqyid.longValue() || !form.getClbh().equals(bus.getClbh())){
				//企业不同,标识号不同新增一条过户的历史信息
				YwYnBustransfer entity=YwYnBustransferConvertor.convertTotransfer(bus);
				entity.setGhrq(new Date());
				//设置原来的记录信息
				entity.setQyid(qyid);
				entity.setBzh(entity.getBzh());
				//查询审核完成的年审审验
				List<YwYnBusinfoNssy> nssys=this.ywYnBusinfoNssyService.getNssyByBusId(bus.getId(), "0");
				if(nssys.size()>0){
					//设置年审审验的id
					entity.setNssyId(nssys.get(0).getId());
					//以前有过年审记录才保存一条过户之前的记录
					ywYnBustransferService.saveEntity(entity);
				}
				//保存车辆最新的信息
				this.save(form);
			}else{
				this.save(form);
			}
		}else{
			this.save(form);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService#deleteEntity(java.lang.Long)
	 */
	@Override
	public void deleteEntity(Long id) {
		YwYnBusinfo bus=ywYnBusinfoDao.get(id);
		bus.setDelsts("1");
		this.ywYnBusinfoDao.save(bus);
		
	}

	@Override
	public Page<YwYnBusinfoForm> searchDelBus(Page<YwYnBusinfoForm> page,
			YwYnBusinfoForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx where 1=1 and ps.delsts='1' and ps.qyid = qyxx.id ");
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			
			if(StringUtils.isNotBlank(form.getGsmc())){
				hql.append(" and qyxx.sqdw like '%"+form.getGsmc()+"%'");
			}
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		}
		
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		// 执行分页查询操作
		ywYnBusinfoDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = this.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	@Override
	public Page<YwYnBusinfoForm> findBusData(Page<YwYnBusinfoForm> page,
			YwYnBusinfoForm form,String sfhg) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		StringBuffer hql=null;
		 if (StringUtils.isNotBlank(sfhg)) {
				// 查询语句及参数
			    hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx,\r");
								hql.append(" YwYnBusinfoHfqk hfqk ");
								hql.append(" where hfqk.busId=ps.id and  ps.qyid = qyxx.id \r" );
								hql.append(" and hfqk.yxjsrq in \r");
								hql.append(" (select max(yxjsrq) from YwYnBusinfoHfqk where sts='0' group by busId )");
		 }else{
				// 查询语句及参数
			    hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx\r");
								hql.append(" where 	ps.qyid = qyxx.id \r" );
														
		 }
	
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		    if (StringUtils.isNotBlank(form.getClbh())) {
		        hql.append(" and ps.clbh like '%" + form.getClbh() + "%'");
		    }
		    if (StringUtils.isNotBlank(form.getCllx())) {
		        hql.append(" and ps.cllx ='" + form.getCllx() + "'");
		    }
		    if (StringUtils.isNotBlank(form.getYwtzs())) {
		        hql.append(" and ps.ywtzs ='" + form.getYwtzs() + "'");
		    }
		    
		    if (StringUtils.isNotBlank(sfhg)) {
		    	if("合格".equals(sfhg)){
		    		 hql.append(" and hfqk.yxjsrq>=sysdate");
		    	}else{
		    		hql.append(" and hfqk.yxjsrq<sysdate");
		    	}
		       
		    }
		}
		if(form.getQyid()!=null){
			//排序
			hql.append(" order by ps.cphm asc");
		}else{
			//排序
			hql.append(" order by qyxx.id desc");
		}
		
		// 执行分页查询操作
		ywYnBusinfoDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = this.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	@Override
	public String findZzl(YwYnBusinfoForm form) {
		StringBuffer hql=new StringBuffer(" select sum(to_number(t.zzl))  as zzls  from YW_YN_BUSINFO t, YW_COM_QYXX qyxx where   t.qyid = qyxx.id ");
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and t.cphm like '%" + form.getCphm() + "%'");
		    }
		    if (StringUtils.isNotBlank(form.getClbh())) {
		        hql.append(" and t.clbh like '%" + form.getClbh() + "%'");
		    }
		    if (StringUtils.isNotBlank(form.getCllx())) {
		        hql.append(" and t.cllx ='" + form.getCllx() + "'");
		    }
		    if (StringUtils.isNotBlank(form.getYwtzs())) {
		        hql.append(" and t.ywtzs ='" + form.getYwtzs() + "'");
		    }
		}
		Query query=this.ywYnBusinfoDao.getSession().createSQLQuery(hql.toString());
		List list=query.list();
		if(list.size()>0){
			BigDecimal zzls=(BigDecimal) list.get(0);
			if(zzls!=null){
				return zzls.toString();
			}
			
		}
		return "0";
		
	}

	/*
	 * 获取顺延有效期
	 * @see com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService#searchSyyxq(org.springside.modules.orm.Page, com.augurit.gzcgwsp.ljzyz.web.form.YwYnBusinfoForm)
	 */
	@Override
	public Page<YwYnBusinfoForm> searchSyyxq(Page<YwYnBusinfoForm> page,
			YwYnBusinfoForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx where   ps.qyid = qyxx.id ");
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		    if (StringUtils.isNotBlank(form.getClbh())) {
		        hql.append(" and ps.clbh like '%" + form.getClbh() + "%'");
		    }
		    if (StringUtils.isNotBlank(form.getCllx())) {
		        hql.append(" and ps.cllx ='" + form.getCllx() + "'");
		    }
		    if (StringUtils.isNotBlank(form.getYwtzs())) {
		        hql.append(" and ps.ywtzs ='" + form.getYwtzs() + "'");
		    }
		}
		if(form.getQyid()!=null){
			//排序
			hql.append(" order by ps.cphm asc");
		}else{
			//排序
			hql.append(" order by qyxx.id desc");
		}
		
		// 执行分页查询操作
		ywYnBusinfoDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = this.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	/*
	 * 获取准运证有效期(non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService#getZyzyxqByBusId(java.lang.Long)
	 */
	@Override
	public String getZyzyxqByBusId(Long busId) {
		String sql=" select hfqk from YwYnBusinfoHfqk hfqk,YwYnBusinfoNssy " +
				"nssy where hfqk.nssyId=nssy.id and nssy.busId="+busId+" and nssy.sts='0' and hfqk.sts='0' and hfqk.yxksrq is not null " +
						" order by hfqk.yxjsrq  desc ";
		Query query=this.ywYnBusinfoDao.getSession().createQuery(sql);
		List<YwYnBusinfoHfqk> list=query.list();
		if(list.size()>0){
			Date ksrq=list.get(0).getYxksrq();
			Date jsrq=list.get(0).getYxjsrq();
			return DateUtilsEX.dateFormate(ksrq, "yyyy-MM-dd")+
			"~"+DateUtilsEX.dateFormate(jsrq, "yyyy-MM-dd");
		}
		return "";
	}

	/*
	 * (non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService#stateBusInfo(java.util.Map)
	 */
	@Override
	public List<String[]> stateBusInfo(Map map) {
		List<String[]> datas=new ArrayList<String[]>();
		String sql="select info.cx,qyxx.sqdw,info.qyid,count(info.id) as zs ,sum(to_number(info.zzl)) as zzzls from YW_YN_BUSINFO info";
				sql+=" ,YW_COM_QYXX qyxx where qyxx.id=info.qyid group by info.qyid,info.cx,qyxx.sqdw";
		//求有效数量
	    String yxsql="select qyxx.sqdw, t.qyid,count(t.id) as yxs,sum(to_number(t.zzl))  as yxzzls  from YW_YN_BUSINFO t ,YW_YN_BUSINFO_HFQK hfqk \r"; 
	    	   yxsql+=" ,YW_COM_QYXX qyxx  where  hfqk.bus_id=t.id   and qyxx.id=t.qyid and hfqk.yxjsrq in \r"; 
	    	   yxsql+=" (select max(maxhfqk.yxjsrq) from YW_YN_BUSINFO_HFQK maxhfqk where maxhfqk.sts='0' and maxhfqk.id=hfqk.id group by maxhfqk.bus_id )";
	    	   yxsql+=" and hfqk.yxjsrq>=sysdate group by t.qyid,qyxx.sqdw"; 
        List<Map> zslist=ywYnBusinfoDao.queryForList(sql);
        Map<String,Integer> tempMap=new HashMap<String,Integer>();//临时总数map
        Map<String,Double> tempMap1=new HashMap<String,Double>();//临时载重数map
        Map<String,String> tempMap2=new HashMap<String,String>();//临时车型map
        Map<String,Integer> tempMap3=new HashMap<String,Integer>();//临时车型数map
        Map<String,Integer> yxnumMap=new HashMap<String,Integer>();//有效车型数map
        Map<String,Double> yxzzlMap=new HashMap<String,Double>();//有效载重数
		for(Map zs:zslist){
			String sqdw=(String) zs.get("sqdw");
			int countnum=(String) zs.get("zs")==null?0:Integer.valueOf((String) zs.get("zs"));//总数
			double zzzls=(String) zs.get("zzzls")==null?0:Double.valueOf((String) zs.get("zzzls"));//总载重数
			String cx=(String) zs.get("cx");//车型
			int tempnum=(Integer) tempMap.get(sqdw)==null?0:tempMap.get(sqdw);//总数
			double tempzzl=(Double) tempMap1.get(sqdw)==null?0.00: tempMap1.get(sqdw);//总载重数
			String tempcx=(String) tempMap2.get(sqdw)==null?"":tempMap2.get(sqdw);//车型
			int tempcxcount=(Integer) tempMap3.get(sqdw)==null?0: tempMap3.get(sqdw);//车型数
			if(tempnum>0 && StringUtils.isNotBlank(cx) && 
					tempcx.indexOf(cx)<0){
				tempcxcount+=1;
				tempnum+=countnum;
				tempzzl+=zzzls;
				tempcx+=cx+",";
			}else{
				tempcx=cx;
				tempcxcount=1;
				tempnum=countnum;
				tempzzl=zzzls;
			}
			tempMap.put(sqdw, tempnum);//车辆总数
			tempMap1.put(sqdw, tempzzl);//总载重数
			tempMap2.put(sqdw, tempcx);
			tempMap3.put(sqdw, tempcxcount);//车型总数
		}
        List<Map> yxlist=ywYnBusinfoDao.queryForList(yxsql);
        for(Map yxzs:yxlist){//取有效总数
        	String sqdw=(String) yxzs.get("sqdw");
        	String yxsnum=(String) yxzs.get("yxs");
        	String yxzzl=(String) yxzs.get("yxzzls");
        	yxnumMap.put(sqdw, Integer.valueOf(yxsnum));
        	yxzzlMap.put(sqdw, Double.valueOf(yxzzl));
        }
        //取数据
        for( Map.Entry<String,Integer> entry:tempMap.entrySet()){
        	String[] data=new String[6];
        	String sqdw=entry.getKey();
        	int countnum=tempMap.get(sqdw);//车辆总数
			double zzlzs=tempMap1.get(sqdw);//总载重数
			int yxnum=yxnumMap.get(sqdw)==null?0:yxnumMap.get(sqdw);//有效车辆数
        	double yxzzl=yxzzlMap.get(sqdw)==null?0:yxzzlMap.get(sqdw);//有效载重量
        	int cxnum=tempMap3.get(sqdw);//车型总数
        	data[0]=sqdw;
        	data[1]=String.valueOf(countnum);
        	data[2]=String.valueOf(yxnum);
        	data[3]=String.valueOf(zzlzs);
        	data[4]=String.valueOf(yxzzl);
        	data[5]=String.valueOf(cxnum);
        	datas.add(data);
        }
		return datas;
	}

	@Override
	public Long getBusQyid(String carsts, String nssysts) {
		String hql="select info.qyid from YwYnBusinfo info where info.id in(select max(t.id) from YwYnBusinfo t where " +
				" t.nssts='"+nssysts+"' )";
		List list=this.ywYnBusinfoDao.find(hql);
		if(list.size()>0){
			return (Long)list.get(0);
		}
		return null;
	}

	@Override
	public YwYnBusinfoForm getBusByNo(String cphm) {
		String hql=" from YwYnBusinfo info where info.cphm='" +cphm+"'";
	List list=this.ywYnBusinfoDao.find(hql);
	if(list.size()>0){
		YwYnBusinfo entity=(YwYnBusinfo)list.get(0);
		return YwYnBusinfoConvertor.convertVoToForm(entity);
	}
		return null;
	}

	@Override
	public YwYnBusinfoForm getBusByNo(String cphm, String clbh) {
		String hql=" from YwYnBusinfo info where info.cphm='" +cphm+"' and clbh='"+clbh+"'";
		List list=this.ywYnBusinfoDao.find(hql);
		if(list.size()>0){
			YwYnBusinfo entity=(YwYnBusinfo)list.get(0);
			return YwYnBusinfoConvertor.convertVoToForm(entity);
		}
			return null;
		}

	@Override
	public String saveCarInfo(YwYnBusinfoForm form) {
		String flag="true";
	  try {
		 Long id=form.getId();
		 String bussql=" from YwYnBusinfo where id="+id;
		 YwYnBusinfo entity = null;
		 List<YwYnBusinfo> listbus=this.ywYnBusinfoDao.find(bussql);
		 if(listbus.size()>0){
			 entity=listbus.get(0);
			
		 }
		 
		 YwComQyxx qyxx=ywComQyxxService.getEntity(form.getGsmc().trim(), "jzljczz");
		 if(qyxx==null){
			 qyxx =new YwComQyxx();
			 qyxx.setSqdw(form.getGsmc());
			 qyxx.setTemplateCode("jzljczz");
			 Long qyxxid=ywComQyxxService.saveQyxx(qyxx);
			 qyxx.setId(qyxxid);
		 }
		 if(entity==null){
			 entity=new YwYnBusinfo();
			 YwYnBusinfoConvertor.convertFormToVo(form, entity);
			 entity.setId(null);
			 entity.setQyid(qyxx.getId());
			 ywYnBusinfoDao.save(entity);
			 form.setId(entity.getId());
		 }
		 
		  Long carid=form.getId();
		  //年审审验
		  YwYnBusinfoNssyForm nssy=saveNssy(String.valueOf(carid), form.getSysfhg(), form.getSybgbh());
		  //核发情况保存
		  this.saveHfqk(form, nssy);
	} catch (RuntimeException e) {
		flag="false";
		e.printStackTrace();
	}
	  
	  return flag;
	}
	/**
	 * 保存核发情况
	 * @param busId
	 * @param sysfhg
	 * @param sybgbh
	 */
	private void saveHfqk(YwYnBusinfoForm bus,YwYnBusinfoNssyForm nssy){
		YwYnBusinfoHfqkForm form=new YwYnBusinfoHfqkForm();
		form.setBusId(Long.valueOf(bus.getId()));
		form.setNssyId(nssy.getId());
		form.setYxksrq(bus.getYxksrq());
		form.setYxjsrq(bus.getYxjsrq());
		form.setJcrq(bus.getJcrq());
		form.setSts("0");
		//设置默认的有效开始和结束时间
		if(form.getYxksrq()==null){
			form.setYxksrq(new Date());
		}
		if(form.getYxjsrq()==null){
			Date date=DateUtilsEX.getDateByMonth(form.getYxksrq(), 6,true);
			form.setYxjsrq(date);
		}
		//核发的时候
		form.setSffbzp("发证");
		form.setJyy(bus.getJyy());
			 //科审批
		form.setKspr(bus.getKspr());
		form.setKspjg("同意发证");
		form.setKspyj("同意");
		 //副处长审批
		//if(form.getFgcspr()==null){
		form.setFgcspr(bus.getFgcspr());
		//}
		//if(form.getFgcspjg()==null){
		form.setFgcspjg("同意发证");
		//}
		//if(form.getFgcspyj()==null){
		form.setFgcspyj("同意");
		//}
		 //处长审批
		//if(form.getCspr()==null){
		form.setCspr(bus.getCspr());
		//}
		//if(form.getCspjg()==null){
		form.setCspjg("同意发证");
		//}
		//if(form.getCspyj()==null){
		form.setCspyj("同意");
		//}
		form.setXbzh(bus.getBzh());
		form.setXclbh(bus.getCphm());
		form.setBzplsh(bus.getBzplsh());
		ywYnBusinfoHfqkService.save(form);
	}
	
	/**
	 * 
	 * @param busId
	 * @param sysfhg 审验是否合格
	 * @param sybgbh 审验报告编号
	 */
	private YwYnBusinfoNssyForm saveNssy(String busId,String sysfhg,String sybgbh){
		YwYnBusinfoNssyForm form=new YwYnBusinfoNssyForm();
		form.setBusId(Long.valueOf(busId));
		form.setXszsfgx("有");
		form.setBzp("合格");
		form.setSfns("有");
		form.setCp("合格");
		form.setDg("合格");
		form.setLunt("合格");
		form.setCrck("合格");
		form.setBzp("合格");
		form.setCr("合格");
		form.setYs("合格");
		form.setCmpz("合格");
		form.setSgmfx("合格");
		form.setWmxwm("合格");
		form.setFlcwg("合格");
		form.setSyxj("合格");
		form.setZhsyjl("合格");
		form.setJjzdSyxj("合格");
		form.setShwjSyxj("合格");
		form.setSysfhg(sysfhg);
		form.setSybgbh(sybgbh);
		form.setSts("0");
		this.ywYnBusinfoNssyService.save(form,true);
		return form;
	}
}
